//
//  ViewController.m
//  测试demo
//
//  Created by ycx on 2019/6/27.
//  Copyright © 2019 ycx. All rights reserved.
//

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

#import "DataModel.h"
#import "LightSensitive.h"
#import "DistanceSensor.h"
#import "AccelerometerSensor.h"

double DegreesToRadians(double degrees) {return degrees * M_PI / 180;};
double RadiansToDegrees(double radians) {return radians * 180 / M_PI;};

static NSString * mapData = @"mapData";



@interface ViewController ()<CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *latitudeLab;
@property (weak, nonatomic) IBOutlet UILabel *longitudeLab;
@property (weak, nonatomic) IBOutlet UILabel *heightLab;
@property (weak, nonatomic) IBOutlet UILabel *speedLab;
@property (weak, nonatomic) IBOutlet UILabel *courseLab;
@property (weak, nonatomic) IBOutlet UILabel *timeLab;
@property (weak, nonatomic) IBOutlet UILabel *currentspeedLab;
@property (weak, nonatomic) IBOutlet UILabel *avgspeedLab;
@property (weak, nonatomic) IBOutlet UILabel *distanceLab;
@property (weak, nonatomic) IBOutlet UILabel *currentdirectionLab;


@property (nonatomic ,strong) CLLocationManager* locationManager;
@property(nonatomic,strong)CLLocation * prevLocation;
@property(nonatomic,assign)NSTimeInterval sumTime;
@property(nonatomic,assign)CGFloat sumDistance;
@property(nonatomic,assign)CGFloat currentSpeed;
@property(nonatomic,assign)CGFloat avgSpeed;
@property(nonatomic,assign)CGFloat currentMaxSpeed;
@property(nonatomic,assign)CGFloat currentMinSpeed;
@property(nonatomic,copy)NSString * currentdirection;
@property(nonatomic,strong)NSTimer * locationTimer;



@property(nonatomic,assign)double  magneticHeading;
@property(nonatomic,assign)CGFloat magneticHeadingAngel;

@property(nonatomic,assign)double  trueHeading;
@property(nonatomic,assign)double  headingAccuracy;
@property(nonatomic,assign)double  headingX;
@property(nonatomic,assign)double  headingY;
@property(nonatomic,assign)double  headingZ;

@property(nonatomic,assign)double gravityX;
@property(nonatomic,assign)double gravityY;
@property(nonatomic,assign)double gravityZ;

@property(nonatomic,assign)double yaw;
@property(nonatomic,assign)double pitch;
@property(nonatomic,assign)double roll;

@property(nonatomic,assign)double rotationRateX;
@property(nonatomic,assign)double rotationRateY;
@property(nonatomic,assign)double rotationRateZ;

@property(nonatomic,assign)double userAccelerationX;
@property(nonatomic,assign)double userAccelerationY;
@property(nonatomic,assign)double userAccelerationZ;

@property(nonatomic,assign)double magneticFieldX;
@property(nonatomic,assign)double magneticFieldY;
@property(nonatomic,assign)double magneticFieldZ;



@property(nonatomic,strong)LightSensitive * lightsensitive;
@property(nonatomic,strong)DistanceSensor * distancesensor;
@property(nonatomic,strong)AccelerometerSensor * accelerometersensor;

@property(nonatomic,assign)int  turnLeft;
@property(nonatomic,assign)int  turnRight;
@property(nonatomic,assign)int  addSpeed;
@property(nonatomic,assign)int  cutSpeed;





@end

@implementation ViewController
- (IBAction)locationBtnClick:(id)sender {
    UIButton * btn = (UIButton *)sender;
    
    
    if([btn.titleLabel.text isEqualToString:@"开启定位"])
    {
        [btn setTitle:@"停止定位" forState:UIControlStateNormal];
        self.locationTimer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(startLocationService) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.locationTimer forMode:NSRunLoopCommonModes];
    
    }else
    {
        //开始监听定位信息
        [self.locationTimer invalidate];
        [btn setTitle:@"开启定位" forState:UIControlStateNormal];
        NSMutableArray * dataArray = [[[NSUserDefaults standardUserDefaults] objectForKey:mapData] mutableCopy];
        NSString * text = [self ArrayToJSON:dataArray];
        NSLog(@"%@",text);
        
    }
}
-(void)startLocationService
{
    // NSLog(@"定时器掉用");
    //如果定位服务可用
    if ([CLLocationManager locationServicesEnabled]) {
        NSLog(@"开始执行定位服务");
        self.locationManager.pausesLocationUpdatesAutomatically = NO;
        //设置定位精度：最佳精度
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设置距离过滤器为50米，表示每移动50米更新一次位置
        self.locationManager.distanceFilter = kCLDistanceFilterNone;
        self.locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        //将试图控制器自身设置为CLLocationManager的delegate
        //因此该试图控制器需要实现CLLocationManagerDelegate协议
        self.locationManager.delegate = self;
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
        {
            [self.locationManager requestWhenInUseAuthorization];
            [self.locationManager requestAlwaysAuthorization];
        }
        if([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)
        {
            self.locationManager.allowsBackgroundLocationUpdates = YES;
        }
        //开始监听定位信息
        [self.locationManager startUpdatingLocation];
        // 如果磁力计可用，则开始监听方向改变
    
    }else{
        NSLog(@"无法使用定位服务！！！");
    }
    
    if([CLLocationManager headingAvailable])
    {
        self.locationManager.headingFilter = kCLHeadingFilterNone;
        [self.locationManager startUpdatingHeading];
    }
    
    
    __weak typeof(self)weakSelf = self;
    [self.accelerometersensor initialization:^(CMDeviceMotion * _Nonnull motion) {
        

        
            //2. Gravity  获取手机的重力值在各个方向上的分量，根据这个就可以获得手机的空间位置，倾斜角度等
            //重力加速度在各个方向的分量
            weakSelf.gravityX = motion.gravity.x;
            weakSelf.gravityY = motion.gravity.y;
            weakSelf.gravityZ = motion.gravity.z;
            NSLog(@"\n重力:\nX：%f\nY：%f\nZ：%f", weakSelf.gravityX, weakSelf.gravityY, weakSelf.gravityZ);
    
        //获取手机的倾斜角度(zTheta是手机与水平面的夹角， xyTheta是手机绕自身旋转的角度)：
        double zTheta = atan2(weakSelf.gravityZ,sqrtf(weakSelf.gravityX*weakSelf.gravityX+weakSelf.gravityY*weakSelf.gravityY))/M_PI*180.0;
        double xyTheta = atan2(weakSelf.gravityX,weakSelf.gravityY)/M_PI*180.0;
        NSLog(@"\n与水平夹角: %f\n自身旋转角度：%f", zTheta, xyTheta);
        
        
        
        weakSelf.yaw = motion.attitude.yaw;
        weakSelf.pitch = motion.attitude.pitch;
        weakSelf.roll = motion.attitude.roll;
    
        //            NSLog(@"手机顶部转过的夹角（Z轴倾斜）：%lf",deviceMotion.attitude.yaw);
        //
        //            NSLog(@"手机顶部或尾部翘起角度（X轴倾斜）：%lf",deviceMotion.attitude.pitch);
        //
        //            NSLog(@"手机左右侧翘起角度：（Y轴倾斜）%lf",deviceMotion.attitude.roll);
        
        //陀螺仪信息
        
        weakSelf.rotationRateX = motion.rotationRate.x;
        weakSelf.rotationRateY = motion.rotationRate.y;
        weakSelf.rotationRateZ = motion.rotationRate.z;
        //            NSLog(@"rotationRate.x==%lf",deviceMotion.rotationRate.x);
        //
        //            NSLog(@"rotationRate.y==%lf",deviceMotion.rotationRate.y);
        //
        //            NSLog(@"rotationRate.z==%lf",deviceMotion.rotationRate.z)
        //
        //用户加速度
        
        weakSelf.userAccelerationX = motion.userAcceleration.x;
        weakSelf.userAccelerationY = motion.userAcceleration.y;
        weakSelf.userAccelerationZ = motion.userAcceleration.z;
        //
        //            NSLog(@"deviceMotion.gravity.x==%lf",deviceMotion.gravity.x);
        //
        //            NSLog(@"deviceMotion.gravity.y==%lf",deviceMotion.gravity.y);
        //
        //            NSLog(@"deviceMotion.gravity.z==%lf",deviceMotion.gravity.z);
        //
        //            //磁场信息（精度）
        //
        //            NSLog(@"%d",deviceMotion.magneticField.accuracy);
        //
        //xyz磁场强度
        
        weakSelf.magneticFieldX = motion.magneticField.field.x;
        weakSelf.magneticFieldY = motion.magneticField.field.y;
        weakSelf.magneticFieldZ = motion.magneticField.field.z;
        //
        //            NSLog(@"%lf",deviceM  otion.magneticField.field.x);
        //
        //            NSLog(@"%lf",deviceMotion.magneticField.field.y);
        //
        //            NSLog(@"%lf",deviceMotion.magneticField.field.z);
    }];
  

    
}
-(void)stopLocationService
{
    //开始监听定位信息
    [self.locationManager stopUpdatingLocation];
    [self.locationManager stopUpdatingHeading];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading{
    
    
    // magneticHeading : 距离磁北方向的角度
    // trueHeading : 真北
    // headingAccuracy : 如果是负数,代表当前设备朝向不可用
    if (newHeading.headingAccuracy < 0) {
        return;
    }
    /**
     * magneticHeading 表示磁北极偏转的角度
     ＊trueHeading  磁北极的真实角度
     ＊0.0 - 359.9 度, 0 being true North
     */
    
    
    
    
    
    
    self.magneticHeading = newHeading.magneticHeading;
    
    //    NSString *direction = [NSString string];
    //    if (self.magneticHeading < 90) {
    //        direction = @"北";
    //    }else if (self.magneticHeading > 90 && self.magneticHeading < 180){
    //        direction = @"东";
    //        self.magneticHeading = self.magneticHeading - 90;
    //    }else if (self.magneticHeading > 180 && self.magneticHeading < 270){
    //        direction = @"南";
    //    }else if (self.magneticHeading > 270){
    //        direction = @"西";
    //        self.magneticHeading = self.magneticHeading - 270;
    //    }
    
    //将我们的角度转换为弧度
    CGFloat angle= newHeading.magneticHeading/180.0*M_PI;
    self.magneticHeadingAngel = angle;
    self.trueHeading = newHeading.trueHeading;
    self.headingAccuracy = newHeading.headingAccuracy;
    self.headingX = newHeading.x;
    self.headingY = newHeading.y;
    self.headingZ = newHeading.z;
  NSLog(@"磁北:%f,磁北弧度:%f,真北:%f,偏移:%f,x方向:%f,y方向:%f,z方向:%f",self.magneticHeading,self.magneticHeadingAngel,self.trueHeading,self.headingAccuracy,self.headingX,self.headingY,self.headingZ);
    
    [self.locationManager stopUpdatingHeading];
    
}

-(BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager *)manager
{
    return YES;
}

#pragma mark -- CLLocationManagerDelegate
//成功获取定位数据后将会激发该方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //获取最后一个定位数据
    CLLocation* newLocation = [locations lastObject];
    //依次获取CLLocation中封装的经度、纬度、高度、速度、方向等信息
    
    
    if (newLocation.horizontalAccuracy < kCLLocationAccuracyHundredMeters) {
        if (self.prevLocation) {
            //计算本次定位数据与上次定位数据之间的时间差
            NSTimeInterval dTime = [newLocation.timestamp timeIntervalSinceDate:self.prevLocation.timestamp];
            //累计行车时间
            self.sumTime += dTime;
            CGFloat distance = [newLocation distanceFromLocation:self.prevLocation];
            //如果距离小于1米。则忽略本次数据，直接返回该方法
//            if (distance < 5) {
//                return;
//            }
            self.sumDistance += distance;
            //计算移动速度，将米/秒换算成千米/小时，需要乘以3.6
            self.currentSpeed = distance/dTime*3.6;
            //计算平均速度
            self.avgSpeed = self.sumDistance/self.sumTime*3.6;
            NSString* speedFeedback = [NSString stringWithFormat:@"当前速度为：%g千米/小时，平均速度为：%g千米/小时。合计移动：%g前面",self.currentSpeed,self.avgSpeed,self.sumDistance/1000];
            NSLog(@"%@",speedFeedback);
            self.currentdirection = [self bearingToLocationFromCoordinate:self.prevLocation toCoordinate:newLocation];
            self.currentspeedLab.text = [NSString stringWithFormat:@"%g千米/小时",self.currentSpeed];
            self.avgspeedLab.text = [NSString stringWithFormat:@"%g千米/小时",self.avgSpeed];
            self.distanceLab.text = [NSString stringWithFormat:@"%g千米",self.sumDistance/1000];
            self.currentdirectionLab.text = self.currentdirection;
          
        }
        self.prevLocation = newLocation;
        
        NSDate * date = self.prevLocation.timestamp;
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CH"];
        fmt.dateFormat = @"yyyy-MM-dd HH:mm";
        NSString *temp = [fmt stringFromDate:date];
        
        //数据更新
        [self dataDefault];
 
       
       
        self.latitudeLab.text = [NSString stringWithFormat:@"%g",self.prevLocation.coordinate.latitude];
        self.longitudeLab.text = [NSString stringWithFormat:@"%g",self.prevLocation.coordinate.longitude];
        self.heightLab.text = [NSString stringWithFormat:@"%g",self.prevLocation.altitude];
        self.speedLab.text = [NSString stringWithFormat:@"%g",self.prevLocation.speed];
        self.courseLab.text = [NSString stringWithFormat:@"%g",self.prevLocation.course];
        self.timeLab.text = temp;
      NSLog(@"经度:%g,纬度:%g,高度:%g,速度:%g,方向:%g",self.prevLocation.coordinate.latitude,self.prevLocation.coordinate.longitude,self.prevLocation.altitude,self.prevLocation.speed,self.prevLocation.course);
        
          [self.locationManager stopUpdatingLocation];
    }
}
-(void)dataDefault
{
    NSDate * date = self.prevLocation.timestamp;
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CH"];
    fmt.dateFormat = @"yyyy-MM-dd HH:mm";
    NSString *temp = [fmt stringFromDate:date];
    
    NSMutableArray * dataArray = [[[NSUserDefaults standardUserDefaults] objectForKey:mapData] mutableCopy];
    if(dataArray.count>0)
    {
        
        NSMutableDictionary * dataDic =[[NSMutableDictionary alloc] init];
        [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.coordinate.latitude] forKey:@"latitude"];
        [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.coordinate.longitude] forKey:@"longitude"];
        [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.altitude] forKey:@"altitude"];
        [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.speed] forKey:@"speed"];
        [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.course] forKey:@"course"];
        [dataDic setObject:temp forKey:@"timestamp"];
        [dataDic setObject:[NSString stringWithFormat:@"%g千米/小时",self.currentSpeed] forKey:@"currentspeed"];
        [dataDic setObject:[NSString stringWithFormat:@"%g千米/小时",self.avgSpeed] forKey:@"avgSpeed"];
        [dataDic setObject:[NSString stringWithFormat:@"%g千米",self.sumDistance/1000] forKey:@"sumDistance"];
        if(self.currentdirection.length>0)
        {
            [dataDic setObject:self.currentdirection forKey:@"currentdirection"];
        }
        
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.magneticHeading] forKey:@"magneticHeading"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.magneticHeadingAngel] forKey:@"magneticHeadingAngel"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.trueHeading] forKey:@"trueHeading"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.headingAccuracy] forKey:@"headingAccuracy"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.headingX] forKey:@"headingX"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.headingY] forKey:@"headingY"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.headingZ] forKey:@"headingZ"];
        
        
        
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.gravityX] forKey:@"gravityX"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.gravityY] forKey:@"gravityY"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.gravityZ] forKey:@"gravityZ"];
        
        
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.yaw] forKey:@"yaw"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.pitch] forKey:@"pitch"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.roll] forKey:@"roll"];
        
        
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.rotationRateX] forKey:@"rotationRateX"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.rotationRateY] forKey:@"rotationRateY"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.rotationRateZ] forKey:@"rotationRateZ"];
        
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.userAccelerationX] forKey:@"userAccelerationX"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.userAccelerationY] forKey:@"userAccelerationY"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.userAccelerationZ] forKey:@"userAccelerationZ"];
        
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.magneticFieldX] forKey:@"magneticFieldX"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.magneticFieldY] forKey:@"magneticFieldY"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.magneticFieldZ] forKey:@"magneticFieldZ"];
        [dataArray addObject:dataDic];
        [[NSUserDefaults standardUserDefaults] setObject:dataArray forKey:mapData];
        
        
        
        
    }else
    {
        dataArray = [[NSMutableArray alloc] init];
        NSMutableDictionary * dataDic =[[NSMutableDictionary alloc] init];
        [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.coordinate.latitude] forKey:@"latitude"];
        [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.coordinate.longitude] forKey:@"longitude"];
        [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.altitude] forKey:@"altitude"];
        [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.speed] forKey:@"speed"];
        [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.course] forKey:@"course"];
        [dataDic setObject:temp forKey:@"timestamp"];
        [dataDic setObject:[NSString stringWithFormat:@"%g千米/小时",self.currentSpeed] forKey:@"currentspeed"];
        [dataDic setObject:[NSString stringWithFormat:@"%g千米/小时",self.avgSpeed] forKey:@"avgSpeed"];
        [dataDic setObject:[NSString stringWithFormat:@"%g千米",self.sumDistance/1000] forKey:@"sumDistance"];
        if(self.currentdirection.length>0)
        {
            [dataDic setObject:self.currentdirection forKey:@"currentdirection"];
        }
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.magneticHeading] forKey:@"magneticHeading"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.magneticHeadingAngel] forKey:@"magneticHeadingAngel"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.trueHeading] forKey:@"trueHeading"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.headingAccuracy] forKey:@"headingAccuracy"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.headingX] forKey:@"headingX"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.headingY] forKey:@"headingY"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.headingZ] forKey:@"headingZ"];
        
        
        
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.gravityX] forKey:@"gravityX"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.gravityY] forKey:@"gravityY"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.gravityZ] forKey:@"gravityZ"];
        
        
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.yaw] forKey:@"yaw"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.pitch] forKey:@"pitch"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.roll] forKey:@"roll"];
        
        
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.rotationRateX] forKey:@"rotationRateX"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.rotationRateY] forKey:@"rotationRateY"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.rotationRateZ] forKey:@"rotationRateZ"];
        
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.userAccelerationX] forKey:@"userAccelerationX"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.userAccelerationY] forKey:@"userAccelerationY"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.userAccelerationZ] forKey:@"userAccelerationZ"];
        
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.magneticFieldX] forKey:@"magneticFieldX"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.magneticFieldY] forKey:@"magneticFieldY"];
        [dataDic setObject:[NSString stringWithFormat:@"%lf",self.magneticFieldZ] forKey:@"magneticFieldZ"];
        [dataArray addObject:dataDic];
        [[NSUserDefaults standardUserDefaults] setObject:dataArray forKey:mapData];
        
        
    }
    
}
//定位失败时激发的方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"定位失败：%@",error);
}

- (NSString *)bearingToLocationFromCoordinate:(CLLocation*)fromLoc toCoordinate:(CLLocation*)toLoc
{
    double lat1 = DegreesToRadians(fromLoc.coordinate.latitude);
    double lon1 = DegreesToRadians(fromLoc.coordinate.longitude);
    
    double lat2 = DegreesToRadians(toLoc.coordinate.latitude);
    double lon2 = DegreesToRadians(toLoc.coordinate.longitude);
    
    double dLon = lon2 - lon1;
    
    double y = sin(dLon) * cos(lat2);
    double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
    double radiansBearing = atan2(y, x);
    
    NSString *str ;
    double aDeg = RadiansToDegrees(radiansBearing);
    
    if (aDeg >= 75 && aDeg <= 105)
    {
        str = @"正东";
    }
    if (aDeg > 15 && aDeg < 75)
    {
        str = @"东北";
    }
    if (aDeg >= -15 && aDeg <= 15)
    {
        str = @"正北";
    }
    if (aDeg > -75 && aDeg < -15)
    {
        str = @"西北";
    }
    if (aDeg >= -105 && aDeg <= -75)
    {
        str = @"正西";
    }
    if (aDeg > -165 && aDeg < -105)
    {
        str = @"西南";
    }
    if ((aDeg >= 165 && aDeg <= 180) || (aDeg >= -180 && aDeg <= -165))
    {
        str = @"正南";
    }
    if (aDeg > 105 && aDeg < 165)
    {
        str = @"东南";
    }
    
    CLLocationDistance meters = [fromLoc distanceFromLocation:toLoc];
    return [NSString stringWithFormat:@"%@%f米", str, meters];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}
- (NSString *)ArrayToJSON:(NSArray *)Arr {
    
    
    NSData *data=[NSJSONSerialization dataWithJSONObject:Arr options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    //去除空格和回车：
    jsonStr = [jsonStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSLog(@"jsonStr==%@",jsonStr);
    return jsonStr;
}
-(CLLocationManager *)locationManager
{
    if(!_locationManager)
    {
        _locationManager = [[CLLocationManager alloc] init];
    }
    return _locationManager;
}

-(LightSensitive *)lightsensitive
{
    if(!_lightsensitive)
    {
        _lightsensitive = [[LightSensitive alloc] init];
    }
    _lightsensitive.block = ^(float brightnessValue) {
        
       // NSLog(@"当前屏幕亮度%f",brightnessValue);
    };
    return _lightsensitive;
    
}
-(DistanceSensor *)distancesensor
{
    if(!_distancesensor)
    {
        _distancesensor = [[DistanceSensor alloc] init];
    }
    _distancesensor.block = ^(BOOL proximityValue) {
      
        if(proximityValue)
        {
            
        }else
        {
            
        }
        
    };
    return _distancesensor;
}
-(AccelerometerSensor *)accelerometersensor
{
    if(!_accelerometersensor)
    {
        _accelerometersensor = [[AccelerometerSensor alloc] init];
    }
    return _accelerometersensor;
    
}
@end
